package main

import (
	"fmt"
	"gitee.com/hexug/go-tools/logger"
	"log"
	"net"
	"net/http"
	"os"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
)

func init() {
	// 设置日志等级为debug，这样可以捕获到调试级别的日志信息。
	logger.Level = "debug"

	// 设置日志输出到控制台，便于在开发和调试过程中直观看到日志信息。
	logger.PrintConsole = true

	// 不保存日志到文件，主要用于快速开发和测试阶段，减少硬盘IO操作。
	logger.SaveFile = true

	// 设置日志文件的保存目录为"./log"，确保日志文件不会无序存储。
	logger.DirPath = "./log"
}

func main() {
	// 设置为生产模式
	gin.SetMode(gin.DebugMode)

	// 创建默认引擎
	r := gin.Default()

	// 根路径接口
	// 请求示例:
	// GET http://localhost/
	// 返回示例:
	// "kubernetes pod-test v0.2!! ClientIP: 127.0.0.1, ServerName: localhost, ServerIP: 192.168.1.100!\n"
	r.GET("/", func(c *gin.Context) {
		hostname, err := os.Hostname()
		if err != nil {
			hostname = "unknown"
		}

		ipAddr := "unknown"
		addrs, err := net.InterfaceAddrs()
		if err == nil {
			for _, addr := range addrs {
				if ipnet, ok := addr.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
					if ipnet.IP.To4() != nil {
						ipAddr = ipnet.IP.String()
						break
					}
				}
			}
		}

		c.String(http.StatusOK, "kubernetes pod-test v0.2!! ClientIP: %s, ServerName: %s, ServerIP: %s!\n",
			c.ClientIP(), hostname, ipAddr)
	})

	// 200状态测试接口
	// 请求示例:
	// GET http://localhost/200
	// 返回示例: "200"（HTTP状态码200）
	// 附加: 会输出INFO级日志"this is a 200 log message"
	r.GET("/200", func(c *gin.Context) {
		logger.L().Info("this is a 200 log message")
		c.String(http.StatusOK, "200")
	})

	// 300状态测试接口
	// 请求示例:
	// GET http://localhost/300
	// 返回示例: "300"（HTTP状态码200）
	// 附加: 会输出WARN级日志"this is a 300 log message"
	r.GET("/300", func(c *gin.Context) {
		logger.L().Warn("this is a 300 log message")
		c.String(http.StatusOK, "300")
	})

	// 400状态测试接口
	// 请求示例:
	// GET http://localhost/400
	// 返回示例: "400"（HTTP状态码400）
	// 附加: 会输出ERROR级日志"this is a 400 log message"
	r.GET("/400", func(c *gin.Context) {
		logger.L().Error("this is a 400 log message")
		c.String(400, "400")
	})

	// 新增日志测试接口组
	logGroup := r.Group("/logs")
	{
		// 调试日志测试：带参数的调试信息
		// 请求示例:
		// GET http://localhost/logs/debug?user_id=123&action=view_profile
		// 返回示例: "debug log printed"（HTTP状态码200）
		// 附加: 会输出DEBUG级日志，包含user_id、action等参数
		logGroup.GET("/debug", func(c *gin.Context) {
			startTime := time.Now()
			userId := c.Query("user_id")
			action := c.Query("action")
			logger.L().Debug("debug log with parameters",
				"user_id", userId,
				"action", action,
				"cost", time.Since(startTime).Milliseconds(),
				"path", c.FullPath())
			c.String(http.StatusOK, "debug log printed")
		})

		// 信息日志测试：用户操作记录
		// 请求示例:
		// POST http://localhost/logs/user/login
		// 请求体: username=alice&password=123456（form-data格式）
		// 返回示例: "login log recorded"（HTTP状态码200）
		// 附加: 会输出INFO级日志，记录用户名和客户端IP
		logGroup.POST("/user/login", func(c *gin.Context) {
			username := c.PostForm("username")
			ip := c.ClientIP()
			logger.L().Infof("user login attempt：用户 %s; IP %s; 时间 %s",
				username,
				ip,
				time.Now().Format("2006-01-02 15:04:05"))
			c.String(http.StatusOK, "login log recorded")
		})

		// 警告日志测试：资源使用警告
		// 请求示例1（正常情况）:
		// GET http://localhost/logs/resource/warn?usage=70
		// 返回示例1: "resource usage checked"（无警告日志）
		// 请求示例2（警告情况）:
		// GET http://localhost/logs/resource/warn?usage=90
		// 返回示例2: "resource usage checked"（会输出WARN级日志，提示内存使用率过高）
		logGroup.GET("/resource/warn", func(c *gin.Context) {
			usageStr := c.Query("usage")
			usage, _ := strconv.Atoi(usageStr)
			if usage > 80 {
				logger.L().Warn("high resource usage detected",
					"usage_percent", usage,
					"resource", "memory",
					"threshold", 80,
					"suggestion", "release unused resources")
			}
			c.String(http.StatusOK, "resource usage checked")
		})

		// 错误日志测试：参数错误场景
		// 请求示例1（正常情况）:
		// GET http://localhost/logs/param/error?id=456
		// 返回示例1: "parameter validated"（输出INFO级日志）
		// 请求示例2（错误情况）:
		// GET http://localhost/logs/param/error?id=abc
		// 返回示例2: "invalid parameter"（HTTP状态码400，输出ERROR级日志提示参数格式错误）
		logGroup.GET("/param/error", func(c *gin.Context) {
			idStr := c.Query("id")
			id, err := strconv.Atoi(idStr)
			if err != nil {
				logger.L().Error("invalid parameter format",
					"param_name", "id",
					"param_value", idStr,
					"error", err.Error(),
					"client_ip", c.ClientIP())
				c.String(http.StatusBadRequest, "invalid parameter")
				return
			}
			logger.L().Info("valid parameter received", "id", id)
			c.String(http.StatusOK, "parameter validated")
		})

		// 复杂业务日志链：模拟订单流程日志
		// 请求示例1（支付成功）:
		// POST http://localhost/logs/order/process
		// 请求体: order_id=ORD123&user_id=U789&pay_status=success（form-data）
		// 返回示例1: "order processed"（输出DEBUG/INFO/WARN级日志链）
		// 请求示例2（支付失败）:
		// POST http://localhost/logs/order/process
		// 请求体: order_id=ORD456&user_id=U000&pay_status=fail（form-data）
		// 返回示例2: "payment failed"（HTTP状态码402，输出ERROR级日志）
		logGroup.POST("/order/process", func(c *gin.Context) {
			orderId := c.PostForm("order_id")
			userId := c.PostForm("user_id")

			// 步骤1：调试日志-开始处理
			logger.L().Debug("starting order processing",
				"order_id", orderId,
				"user_id", userId,
				"step", 1)

			// 步骤2：信息日志-库存检查
			logger.L().Info("checking inventory",
				"order_id", orderId,
				"product_count", 3,
				"step", 2)

			// 步骤3：警告日志-库存不足
			if true { // 模拟库存不足场景
				logger.L().Warn("low inventory warning",
					"order_id", orderId,
					"remaining", 1,
					"required", 3,
					"step", 3)
			}

			// 步骤4：错误日志-支付失败
			payStatus := c.PostForm("pay_status")
			if payStatus == "fail" {
				logger.L().Error("payment processing failed",
					"order_id", orderId,
					"reason", "insufficient balance",
					"amount", 99.99,
					"step", 4)
				c.String(http.StatusPaymentRequired, "payment failed")
				return
			}

			// 步骤5：信息日志-订单完成
			logger.L().Info("order processed successfully",
				"order_id", orderId,
				"total_amount", 99.99,
				"processing_time", 2.3,
				"step", 5)
			c.String(http.StatusOK, "order processed")
		})

		// 性能测试日志：带耗时统计
		// 请求示例:
		// GET http://localhost/logs/performance
		// 返回示例: "performance test done"（根据响应耗时输出INFO/WARN级日志，默认输出WARN）
		// 附加: 模拟100ms耗时操作，超过50ms阈值会触发警告日志
		logGroup.GET("/performance", func(c *gin.Context) {
			start := time.Now()
			// 模拟耗时操作
			time.Sleep(100 * time.Millisecond)
			duration := time.Since(start)

			if duration > 50*time.Millisecond {
				logger.L().Warn("slow response detected",
					"endpoint", "/logs/performance",
					"duration_ms", duration.Milliseconds(),
					"threshold_ms", 50)
			} else {
				logger.L().Info("fast response",
					"endpoint", "/logs/performance",
					"duration_ms", duration.Milliseconds())
			}
			c.String(http.StatusOK, "performance test done")
		})

		// 批量操作日志：带批量数据统计
		// 请求示例1（全成功）:
		// POST http://localhost/logs/batch?count=100
		// 请求体: count=100（form-data）
		// 返回示例1: "batch operation logged"（输出INFO级日志，无失败项）
		// 请求示例2（含失败）:
		// POST http://localhost/logs/batch
		// 请求体: count=50（form-data）
		// 返回示例2: "batch operation logged"（输出ERROR级日志，提示失败比例）
		logGroup.POST("/batch", func(c *gin.Context) {
			countStr := c.PostForm("count")
			count, _ := strconv.Atoi(countStr)

			logger.L().Info("batch operation started",
				"operation", "data_import",
				"total_items", count,
				"timestamp", time.Now())

			// 模拟失败比例（10%）
			failCount := count / 10
			if failCount > 0 {
				logger.L().Error("batch operation has failures",
					"total", count,
					"success", count-failCount,
					"failed", failCount,
					"failure_rate", fmt.Sprintf("%.2f%%", float64(failCount)/float64(count)*100))
			} else {
				logger.L().Info("batch operation completed with no failures",
					"total", count)
			}
			c.String(http.StatusOK, "batch operation logged")
		})
	}

	// 外部调用日志：模拟第三方接口调用
	// 请求示例1（调用成功）:
	// GET http://localhost/external/call?api=https://example.com&success=true
	// 返回示例1: "external call successful"（输出INFO/DEBUG级日志）
	// 请求示例2（调用失败）:
	// GET http://localhost/external/call?api=https://badurl.com&success=false
	// 返回示例2: "external call failed"（HTTP状态码504，输出ERROR级日志）
	r.GET("/external/call", func(c *gin.Context) {
		api := c.Query("api")
		if api == "" {
			api = "https://mock.service.com/data"
		}

		logger.L().Info("calling external service",
			"url", api,
			"method", "GET",
			"timeout", "5s")

		// 模拟调用结果
		success := c.Query("success") != "false"
		if !success {
			logger.L().Error("external service call failed",
				"url", api,
				"error", "connection timeout",
				"retry", true)
			c.String(http.StatusGatewayTimeout, "external call failed")
			return
		}

		logger.L().Debug("external service response",
			"url", api,
			"status", 200,
			"response_time", "120ms")
		c.String(http.StatusOK, "external call successful")
	})

	// 任务接口
	// 请求示例:
	// GET http://localhost/task
	// 返回示例: {"message":"this task"}（HTTP状态码200）
	r.GET("/task", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{
			"message": "this task",
		})
	})

	// 一级接口组 /l1
	l1Group := r.Group("/l1")
	{
		// 请求示例:
		// GET http://localhost/l1
		// 返回示例: {"message":"This is a GET request to /l1"}
		l1Group.GET("", func(c *gin.Context) {
			c.JSON(http.StatusOK, gin.H{
				"message": "This is a GET request to /l1",
			})
		})

		// 请求示例:
		// GET http://localhost/l1/l2
		// 返回示例: {"message":"This is a GET request to /l1/l2"}
		l1Group.GET("/l2", func(c *gin.Context) {
			c.JSON(http.StatusOK, gin.H{
				"message": "This is a GET request to /l1/l2",
			})
		})

		// 请求示例:
		// GET http://localhost/l1/l2a
		// 返回示例: {"message":"This is a GET request to /l1/l2a"}
		l1Group.GET("/l2a", func(c *gin.Context) {
			c.JSON(http.StatusOK, gin.H{
				"message": "This is a GET request to /l1/l2a",
			})
		})

		// 请求示例:
		// GET http://localhost/l1/l2b
		// 返回示例: {"message":"This is a POST request to /l1/l2a"}
		l1Group.GET("/l2b", func(c *gin.Context) {
			c.JSON(http.StatusOK, gin.H{
				"message": "This is a POST request to /l1/l2a",
			})
		})

		// 请求示例:
		// GET http://localhost/l1/l2c
		// 返回示例: {"message":"This is a POST request to /l1/l2c"}
		l1Group.GET("/l2c", func(c *gin.Context) {
			c.JSON(http.StatusOK, gin.H{
				"message": "This is a POST request to /l1/l2c",
			})
		})
	}

	// 一级接口 /l2（GET方法）
	// 请求示例:
	// GET http://localhost/l2
	// 返回示例: {"message":"This is a GET request to /l2"}
	r.GET("/l2", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{
			"message": "This is a GET request to /l2",
		})
	})

	// 一级接口 /l2（POST方法）
	// 请求示例:
	// POST http://localhost/l2（无请求体）
	// 返回示例: {"message":"This is a POST request to /l2"}
	r.POST("/l2", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{
			"message": "This is a POST request to /l2",
		})
	})

	// API v1 组
	apiV1 := r.Group("/api/v1")
	{
		// 产品相关接口
		products := apiV1.Group("/products")
		{
			// 获取产品列表
			// 请求示例:
			// GET http://localhost/api/v1/products
			// 返回示例: {"items":["product1","product2","product3"],"route":"/api/v1/products"}
			products.GET("", func(c *gin.Context) {
				c.JSON(http.StatusOK, gin.H{
					"route": "/api/v1/products",
					"items": []string{"product1", "product2", "product3"},
				})
			})

			// 获取单个产品详情
			// 请求示例1（正常）:
			// GET http://localhost/api/v1/products/1001
			// 返回示例1: {"product":{"id":1001,"name":"product1001"},"route":"/api/v1/products/1001"}
			// 请求示例2（错误）:
			// GET http://localhost/api/v1/products/abc
			// 返回示例2: {"error":"Invalid product ID"}（HTTP状态码400）
			products.GET("/:product_id", func(c *gin.Context) {
				productID, err := strconv.Atoi(c.Param("product_id"))
				if err != nil {
					c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid product ID"})
					return
				}

				c.JSON(http.StatusOK, gin.H{
					"route":   fmt.Sprintf("/api/v1/products/%d", productID),
					"product": gin.H{"id": productID, "name": fmt.Sprintf("product%d", productID)},
				})
			})
		}

		// 订单相关接口
		orders := apiV1.Group("/orders")
		{
			// 获取订单列表
			// 请求示例:
			// GET http://localhost/api/v1/orders
			// 返回示例: {"orders":["orderA","orderB"],"route":"/api/v1/orders"}
			orders.GET("", func(c *gin.Context) {
				c.JSON(http.StatusOK, gin.H{
					"route":  "/api/v1/orders",
					"orders": []string{"orderA", "orderB"},
				})
			})

			// 获取单个订单详情
			// 请求示例1（正常）:
			// GET http://localhost/api/v1/orders/2002
			// 返回示例1: {"order":{"id":2002,"status":"pending"},"route":"/api/v1/orders/2002"}
			// 请求示例2（错误）:
			// GET http://localhost/api/v1/orders/xyz
			// 返回示例2: {"error":"Invalid order ID"}（HTTP状态码400）
			orders.GET("/:order_id", func(c *gin.Context) {
				orderID, err := strconv.Atoi(c.Param("order_id"))
				if err != nil {
					c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid order ID"})
					return
				}

				c.JSON(http.StatusOK, gin.H{
					"route": "/api/v1/orders/" + strconv.Itoa(orderID),
					"order": gin.H{"id": orderID, "status": "pending"},
				})
			})
		}
	}

	// API v2 组
	apiV2 := r.Group("/api/v2")
	{
		// 获取报表列表
		// 请求示例:
		// GET http://localhost/api/v2/reports
		// 返回示例: {"reports":["reportX","reportY"],"route":"/api/v2/reports"}
		apiV2.GET("/reports", func(c *gin.Context) {
			c.JSON(http.StatusOK, gin.H{
				"route":   "/api/v2/reports",
				"reports": []string{"reportX", "reportY"},
			})
		})

		// 获取商品评论列表
		// 请求示例1（正常）:
		// GET http://localhost/api/v2/items/500/reviews
		// 返回示例1: {"reviews":["good","average","excellent"],"route":"/api/v2/items/500/reviews"}
		// 请求示例2（错误）:
		// GET http://localhost/api/v2/items/abc/reviews
		// 返回示例2: {"error":"Invalid item ID"}（HTTP状态码400）
		apiV2.GET("/items/:item_id/reviews", func(c *gin.Context) {
			itemID, err := strconv.Atoi(c.Param("item_id"))
			if err != nil {
				c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid item ID"})
				return
			}

			c.JSON(http.StatusOK, gin.H{
				"route":   fmt.Sprintf("/api/v2/items/%d/reviews", itemID),
				"reviews": []string{"good", "average", "excellent"},
			})
		})
	}

	// 服务状态接口
	// 请求示例:
	// GET http://localhost/status
	// 返回示例: {"status":"running","uptime":"72h"}
	r.GET("/status", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{
			"status": "running",
			"uptime": "72h",
		})
	})

	// 健康检查接口
	// 请求示例:
	// GET http://localhost/health
	// 返回示例: {"health":"ok"}
	r.GET("/health", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{
			"health": "ok",
		})
	})

	// 启动服务（监听80端口）
	log.Println("Starting server on :80")
	if err := r.Run(":80"); err != nil {
		log.Fatalf("Failed to start server: %v", err)
	}
}
